package com.ssm.juc.thread;

import java.util.concurrent.TimeUnit;

/**
 * 线程终止
 */
public class ThreadStopTest implements Runnable {

    @Override
    public void run() {
        int count = 0;
        // 如果发生中断 && count < 1000000 就线程停止
        while (!Thread.currentThread().isInterrupted() && count < 1000000) {
            System.out.println("count = " + count++);

            // sleep 测试
            /*
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("发生异常: InterruptedException");
                // 重新设置中断状态
                Thread.currentThread().interrupt();
            }
             */

            try {
                this.wait(1);
            } catch (Throwable e) {
                e.printStackTrace();
                System.out.println("发生异常: InterruptedException");
                // 重新设置中断状态
                Thread.currentThread().interrupt();
            }
        }
        System.out.println("线程停止： stop thread");
    }


    public static void main(String[] args) throws InterruptedException {
//        Thread thread = new Thread(new ThreadStopTest());
//        thread.start();
//        Thread.sleep(5);
//        thread.interrupt();

        ThreadStopT1 target = new ThreadStopT1();
        Thread threadStopT1 = new Thread(target);
        threadStopT1.start();
        Thread.sleep(5);
        target.setState(1);

    }

    static class ThreadStopT1 implements  Runnable {

        private volatile int state = 0;

        public int getState() {
            return state;
        }

        public void setState(int state) {
            this.state = state;
        }

        @Override
        public void run() {
            int count = 0;
            // 如果发生中断 && count < 1000000 就线程停止
            while (state != 1 && count < 1000000) {
                System.out.println("count = " + count++);
            }
            System.out.println("线程停止： stop thread");
        }
    }
}